'use strict'

// Schema definition for quotes
const quoteSchema = {
  type: 'object',
  properties: {
    text: { type: 'string' },
    author: { type: 'string' },
    category: { type: 'string' },
    likes: { type: 'integer' },
    createdAt: { type: 'string', format: 'date-time' }
  },
  required: ['text', 'author', 'category']
}

// Get quotes collection
const getQuotesCollection = async (fastify) => {
  const db = fastify.mongo.db
  return db.collection('quotes')
}

// Find quotes
const findQuotes = async (fastify, query = {}, limit = 10, skip = 0) => {
  const collection = await getQuotesCollection(fastify)
  return collection.find(query)
    .sort({ createdAt: -1 })
    .skip(skip)
    .limit(limit)
    .toArray()
}

// Find quote by ID
const findQuoteById = async (fastify, id) => {
  const collection = await getQuotesCollection(fastify)
  return collection.findOne({ _id: new fastify.mongo.ObjectId(id) })
}

// Insert quote
const insertQuote = async (fastify, quote) => {
  const collection = await getQuotesCollection(fastify)
  const newQuote = {
    ...quote,
    likes: 0,
    createdAt: new Date().toISOString()
  }
  const result = await collection.insertOne(newQuote)
  return { ...newQuote, _id: result.insertedId }
}

// Like a quote
const likeQuote = async (fastify, id) => {
  const collection = await getQuotesCollection(fastify)
  const result = await collection.findOneAndUpdate(
    { _id: new fastify.mongo.ObjectId(id) },
    { $inc: { likes: 1 } },
    { returnDocument: 'after' }
  )
  return result.value
}

// Delete quote
const deleteQuote = async (fastify, id) => {
  const collection = await getQuotesCollection(fastify)
  return collection.deleteOne({ _id: new fastify.mongo.ObjectId(id) })
}

module.exports = {
  quoteSchema,
  findQuotes,
  findQuoteById,
  insertQuote,
  likeQuote,
  deleteQuote
} 